﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Transform;
using System.Collections;

namespace NHibernateTest
{
    public class EmployeeDao
    {

        public int GetEmployeeCount(string deptName)
        {
            int count = 0;

            ISession session = null;
            ITransaction transaction = null;
            try
            {
                session = HibernateUtil.OpenSession();
                if (null == session)
                {
                    throw new Exception("No Session created!!!");
                }
                transaction = session.BeginTransaction();
        

                //DetachedCriteria detachedCriteria = DetachedCriteria.For(typeof(Employee));
                //detachedCriteria.CreateCriteria("Dept1")
                //    .Add(Restrictions.Eq("DeptName", deptName))
                //    .SetResultTransformer(CriteriaSpecification.DistinctRootEntity);

                //List<Employee> list = (List<Employee>)detachedCriteria.GetExecutableCriteria(session).List<Employee>();

                string hql = "from Employee as emp where emp.Dept1.DeptName = 'A'";
                IQuery query = session.CreateQuery(hql);
                Console.WriteLine(query.QueryString);
                IList l = query.List();
                if (null != l)
                {
                    count = l.Count;
                }
                transaction.Commit();
            }
            catch (Exception e)
            {
                if (null != transaction)
                    transaction.Rollback();
                Console.WriteLine("Error: " + e.Message);
            }
            finally
            {
                HibernateUtil.CloseSession(session);
            }

            return count;
        }

    }
}
